/**
 * @author zy
 */
import { Platform } from 'react-native';
import { STORAGE_CONSTANT } from '../config/storage';
import { API, API_GENERATE } from '../config/api';
import { GLOBAL } from '../config/global';
import JPushModule from 'jpush-react-native';
import Dictionary from '../utils/dictionary';
import StorageHelper from './storageHelper';
import HTTP from './http';

class JPushUtil {
  //监听
  listener() {
    //模拟器状态下获取不到对应的极光连接，不进行极光相关操作
    if (GLOBAL.IS_EMULATOR) return;
    JPushModule.removeReceiveCustomMsgListener();
    JPushModule.removeReceiveNotificationListener();
  }

  //清除  ios 图标右上角消息数字
  clearBadge() {
    //模拟器状态下获取不到对应的极光连接，不进行极光相关操作
    if (GLOBAL.IS_EMULATOR) return;

    if (Platform.OS === 'ios') {
      JPushModule.setBadge(0, (success) => {
        console.log(success)
      });
    }
  }

  // 功能函数
  setJPushModule() {

    //模拟器状态下获取不到对应的极光连接，不进行极光相关操作
    if (GLOBAL.IS_EMULATOR) return;

    this.clearBadge();
    // 安卓在调用方法前需要调用
    if (Platform.OS === 'android') {
      JPushModule.notifyJSDidLoad(resultCode => {
        if (resultCode === 0) {
        }
      }); //这里必须写回调
    }
    // 接收自定义消息
    JPushModule.addReceiveCustomMsgListener((message) => {
      console.log('接收自定义消息', message);
      this.setState({ pushMsg: message });
    });
    // 接收推送通知
    JPushModule.addReceiveNotificationListener((message) => {
      console.log('接收推送通知');
      console.log(message);
    });
    // 获取极光推送用户注册号
    this.getregistrationID();
    // 打开通知
    JPushModule.addReceiveOpenNotificationListener(async (map) => {
      console.log('打开消息', map)
      if (!GLOBAL.TAB_NAVIGATION) return;
      let userId = await this.getUserId();  // 用户登入 id


      let extrasData = map.extras && (typeof (map.extras) == 'string' ? JSON.parse(map.extras) : map.extras);

      console.log('extrasData-new', extrasData);
      let { taskId, taskName,
        orderId, orderType, status, periodType, isFuture, longOrderId, isAgency,
        companyId, companyName, bizStaffId, bizMode
      } = extrasData;


      // 获取标题  业务员 ID
      let orderTypeName = orderType === 'S' ? '销售' : '采购';
      let orderTypeLabel = '';
      let title = '';
      if (periodType === 'L') {
        title = '长约' + orderTypeName + '框架' + (bizStaffId == userId ? '详情' : '审批');
      } else {
        orderTypeLabel = longOrderId && longOrderId != 'null' ? '长约' : (isFuture === 1 ? '远期' : (isAgency == 1 ? '代理' : '现货'));
        title = orderTypeLabel + orderTypeName + '成交报告' + (bizStaffId == userId ? '详情' : '审批');
      }

      // 业务员  -  详情
      if (bizStaffId == userId) {
        GLOBAL.TAB_NAVIGATION.navigate('OrderDetailsPage', { orderId });
      } else { // 其它角色
        if (taskName) {
          let dicData = await Dictionary.init();
          console.log('数据字典-其他角色', dicData, taskName);
          let sendData = {
            orderId,
            orderType,
            companyId,
            businessKey: orderId,
            taskId,
            formKey: taskName,
            companyName,
            auditResultName: '审批中',
            approveType: 'O'
          }
          for (var i = 0; i < dicData['APP_PAGE_FLOW_ROLE_MAPPING'].length; i++) {
            if (dicData['APP_PAGE_FLOW_ROLE_MAPPING'][i].dictKey == taskName) {
              sendData.taskType = dicData.APP_PAGE_FLOW_ROLE_MAPPING[i].comments;
              break;
            }
          }
          GLOBAL.TAB_NAVIGATION.navigate('OrderApprovePage', { status: 'LOT', title: title, paramsData: sendData });
        } else {  // 都不匹配
          GLOBAL.TAB_NAVIGATION.navigate('MessageIndexPage');
        }
      }

    });
  }

  //获取极光推送用户注册号
  getregistrationID() {
    JPushModule.getRegistrationID((rId) => {
      if (rId == '') {
        setTimeout(() => {
          this.getregistrationID();
        }, 1000);
      } else {
        StorageHelper.set(STORAGE_CONSTANT.REGISTRATION_ID, rId);
      }
    });
  }

  //获取userId
  getUserId = async () => {
    let account = null;
    let userId = false;
    try {
      account = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
      account = JSON.parse(account);
      userId = account.userId;
    } catch (error) {
      console.log(error);
    }
    return userId
  }

}

module.exports = new JPushUtil();